package servicebase

import (
	"jkgo/jk/jklog"
	"jkgo/jk/jkprotocol"
	"jkgo/jkbase"
	"time"
)

/*
 * Service port
 * status : 20101
 * dbs : 20102
 * sys : 20103
 */

type ClientBase struct {
	jkbase.JKNetBase
	isConnected bool
}

func (c *ClientBase) KeepaliveCycle(interval time.Duration, id string) error {
	for {
		if !c.IsConnected() {
			time.Sleep(5 * time.Second)
			continue
		}
		str, _ := jkprotocol.JKProtoV6MakeKeepalive(id)
		n := c.Send(str)
		jklog.L().Debugf("Send keepalive %d\n", n)
		if n < 0 {
			c.SetDisconnected()
			continue
		}

		time.Sleep(time.Second * interval)
	}

	return nil
}

// Dial in cycle, with waitAgain for how long check again
func (dc *ClientBase) DialDuring(waitAgain int) {
	go func() {
		for {
			if !dc.isConnected {
				err := dc.Dial()
				if err != nil {
					jklog.L().Errorln("Dial error will again ", err)
					time.Sleep(time.Second * 5)
				} else {
					jklog.L().Infoln("Dial success")
					dc.isConnected = true
				}
			}
		}
	}()
}

// Used for client
func (dc *ClientBase) IsConnected() bool {
	return dc.isConnected
}

func (nb *ClientBase) SetDisconnected() {
	nb.isConnected = false
}
